package com.alibaba.springbootrbac.security;

import com.alibaba.springbootrbac.mapper.RoleMapper;
import com.alibaba.springbootrbac.model.entity.Permission;
import com.alibaba.springbootrbac.model.entity.Role;
import com.alibaba.springbootrbac.model.entity.User;
import com.alibaba.springbootrbac.service.PermissionService;
import com.alibaba.springbootrbac.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ZhouYaDong
 * @date 2025/8/24
 * @description
 */

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Resource
    private UserService userService;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Resource
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        User user = userService.queryByUserName(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 查角色
        List<Role> userRoles = userService.getUserRoles(user.getId());

        // 查权限
        List<Permission> permissions = permissionService.getPermissionsByUserId(user.getId());
        System.out.println("用户: " + username + ", 角色: " + userRoles + ", 权限: " + permissions);

        // 封装权限信息
        List<GrantedAuthority> authorities = new ArrayList<>();
        userRoles.forEach(r -> authorities.add(new SimpleGrantedAuthority("ROLE_" + r.getName())));
        permissions.forEach(p -> authorities.add(new SimpleGrantedAuthority(p.getName())));

        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),  // 这里是加密后的密码
                authorities
        );
    }
}
